package com.itheima.controller;

import com.itheima.common.R;
import com.itheima.pojo.Order;
import com.itheima.pojo.Page;
import com.itheima.service.OrderService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;

/**
 * @author wuyiqiang
 * @2022/6/19 19:46
 */
@RestController
@RequestMapping(value = "/order", produces = "application/json;charset=utf-8")
public class OrderController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 提交订单
     * @param order
     * @param request
     * @return
     * @throws ParseException
     */
    @PostMapping("/submit")
    public R submit(@RequestBody Order order, HttpServletRequest request) throws ParseException {
        //设置用户id
        String userId = tokenToUsername(request);
        order.setUserId(userId);
        //设置当前订单号和id
        order.setId(System.currentTimeMillis() + "");
        order.setNumber(System.currentTimeMillis() + "");
        //设置状态
        order.setStatus(2);
        //设置支付方式
        order.setPayMethod(1);
        //设置下单时间
        order.setOrderTime(LocalDateTime.now());
        //设置结束时间
        order.setCheckoutTime(LocalDateTime.now());

        orderService.submit(order);
        return R.success("提交订单成功");
    }

    @GetMapping("/userPage")
    public R page(@Param("page")Integer page,@Param("pageSize")Integer pageSize){
        R<Page> result = orderService.page(page, pageSize);
        return result;
    }

    /**
     * 利用token获得当前页面用户名
     *
     * @param request
     * @return
     */
    public String tokenToUsername(HttpServletRequest request) {
        //用户id设置
        String token = request.getHeader("AuthorizationUser");

        String username = (String) redisTemplate.opsForValue().get(token);


        return username;
    }
}
